<template>
    <div>
        <a-form-model
                ref="ruleForm"
                :model="params"
                layout="inline"
                class="search-form"
        >
            <a-card>
                <a-form-model-item label="流程分类" prop="categoryId">
                    <category-select v-model="params.categoryId"></category-select>
                </a-form-model-item>
                <a-form-model-item label="流程名称" prop="name">
                    <a-input v-model="params.processDefinitionName" placeholder="流程名称"/>
                </a-form-model-item>
                <a-form-model-item label="模型key" prop="key">
                    <a-input v-model="params.processDefinitionKey" placeholder="流程key"/>
                </a-form-model-item>
                <a-form-model-item>
                    <a-button type="primary" @click="handleSearch">
                        搜索
                    </a-button>
                    <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
                        重置
                    </a-button>
                </a-form-model-item>
            </a-card>
        </a-form-model>
        <a-card>
            <div>
                <a-button type="primary" @click="() => onImport()">
                    导入流程
                </a-button>
            </div>
            <a-table
                    bordered
                    :columns="columns"
                    :row-key="record => record.id"
                    :data-source="data"
                    :pagination="pagination"
                    :loading="loading"
                    size="middle"
                    @change="handleTableChange"
            >
                <template slot="suspended" slot-scope="text , record">
                    <a-switch
                              checked-children="启用"
                              un-checked-children="禁用"
                              :loading="record.loading"
                              @change="onStateChange(record)"
                              :checked="!record.suspended"/>
                </template>
                <template slot="operation" slot-scope="text , record">
                    <a-popconfirm
                            title="确定删除吗?"
                            @confirm="() => onDelete(record)"
                    >
                        <a href="javascript:;">删除</a>
                    </a-popconfirm>
                    <a-divider type="vertical"/>
                    <a @click="() => onDownload(record)">导出</a>
                    <a-divider type="vertical"/>
                    <a @click="() => onStart(record)">发起流程</a>
                </template>
            </a-table>
        </a-card>

        <a-modal
                :title="modalTitle"
                :visible="visible"
                :confirm-loading="confirmLoading"
                @ok="handleOk"
                @cancel="handleCancel"
        >
            <import-form ref="form" @done="onSubmitDone"/>
        </a-modal>
    </div>

</template>
<script>
import { statusMap, page, remove, updateState } from '@/api/process'
import ImportForm from './components/ImportForm'
import CategorySelect from '../category/components/CategorySelect'

export default {
  name: 'ProcessDeploy',
  components: {
    ImportForm,
    CategorySelect
  },
  data() {
    return {
      columns: [
        {
          title: '流程ID',
          dataIndex: 'id',
          ellipsis: true
        },
        {
          title: '流程key',
          dataIndex: 'key',
          ellipsis: true
        },
        {
          title: '流程名称',
          dataIndex: 'name',
          ellipsis: true
        },
        {
          title: '分类',
          dataIndex: 'categoryName',
          ellipsis: true
        },
        {
          title: '版本号',
          dataIndex: 'version',
          ellipsis: true
        },
        {
          title: '发布时间',
          dataIndex: 'deploymentTime',
          ellipsis: true
        },
        {
          title: '状态',
          dataIndex: 'suspended',
          ellipsis: true,
          scopedSlots: { customRender: 'suspended' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      loading: false,
      confirmLoading: false,
      modalTitle: '',
      visible: false,
      pagination: { showSizeChanger: true, showTotal: total => `共 ${total} 条数据` },
      params: {
        page: 1,
        limit: 10,
        processDefinitionKey: '',
        processDefinitionName: '',
        category: ''
      },
      statusMap: statusMap,
      data: []
    }
  },
  created() {
      this.handleLoad()
  },
  methods: {
    handleSearch() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.params.page = 1
          this.handleLoad()
        }
        return false
      })
    },
    handleReset() {
      this.$refs.ruleForm.resetFields()
    },
    handleTableChange(pagination, filters, sorter) {
      this.params = {
        ...this.params,
        limit: pagination.pageSize,
        page: pagination.current
      }
      this.handleLoad()
    },
    handleLoad(params) {
      this.loading = true
      if (params) {
        this.params = { ...this.params, ...params }
      }
      this.pagination.current = this.params.page
      page(this.params).then(({ data }) => {
        const pagination = { ...this.pagination }
        this.data = data.records
        pagination.total = data.total
        this.pagination = pagination
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleOk(e) {
      this.confirmLoading = true
      this.$refs.form.onSubmit()
    },
    handleCancel(e) {
      this.$refs.form.resetForm()
      this.visible = false
    },
    onImport(row) {
      this.modalTitle = '导入流程'
      this.visible = true
    },
    onSubmitDone(success) {
      this.confirmLoading = false
      if (success) {
        this.handleCancel()
        this.handleLoad()
      }
    },
    onDelete(row) {
      remove({ deploymentId: row.deploymentId }).then(res => {
        res.success ? this.$message.success('删除成功') : this.$message.error('删除失败')
        this.handleLoad({ page: 1 })
      })
    },
    onEditor(row) {
      this.$router.push({
        path: '/model/editor',
        query: {
          id: row.id
        }
      })
    },
    onStateChange(row) {
      row.loading = true
      const state = row.suspended ? 'active' : 'suspend'
      updateState({ state: state, processDefinitionId: row.id }).then(res => {
        if (res.success) {
          row.suspended = !row.suspended
          this.$message.success('更新成功')
        } else {
          this.$message.success('更新失败')
        }
        row.loading = false
      })
    },
    onDownload(row) {
      window.open(`${this.$http.defaults.baseURL}/bpm/process/download?processDefinitionId=${row.id}&access_token=${this.$store.getters['user/getToken']}`)
    },
    onSelectChange(id) {
      this.params.category = id
      this.handleLoad()
    },
    onStart(row) {
      const r = this.$router.resolve({ path: '/process/form/start', query: { processKey: row.key }})
      window.open(r.href, '_blank')
    }
  }
}
</script>
